package com.leung.machine.config;


import com.leung.machine.enums.Events;
import com.leung.machine.enums.States;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;

import javax.annotation.Resource;
import java.util.EnumSet;

/**
 * @author 丨一
 * @version 1.0
 * @title StateMachineConfig
 * @description:
 * @date 2025/10/7 上午10:50
 */

@Configuration
@EnableStateMachineFactory
public class StateMachineConfig extends StateMachineConfigurerAdapter<States, Events> {


    @Resource
    private StateMachineListenerAdapter<States, Events> orderStateMachineListener;

    @Override
    public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception {
        states.withStates()
                .initial(States.NEW)
                .states(EnumSet.allOf(States.class));
    }

    //构造状态主转换链
    @Override
    public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception {
        transitions.withExternal()
                .source(States.NEW).target(States.PENDING).event(Events.CREATE)
                .and().withExternal()
                .source(States.PENDING).target(States.COMPLETED).event(Events.COMPLETE)
                .and().withExternal()
                .source(States.PENDING).target(States.FAILED).event(Events.FAIL);
    }

    @Override
    public void configure(StateMachineConfigurationConfigurer<States, Events> config) throws Exception {
        config.withConfiguration()
                .listener(orderStateMachineListener);
    }
}
